<template>
  <div class="page-box">
    <el-divider style="margin: 8px 0;color: black;"></el-divider>

    <!-- 1. 五个指标方块 -->
    <el-row type="flex" justify="center" :gutter="20">
      <el-col v-for="(item, idx) in data" :key="idx" :span="4">
        <div class="grid-box" :class="`color-${idx}`">

          <!-- 不同文字 -->
          <el-popover placement="bottom" title="提示" width="200" trigger="click" :content="item.tip">
            <i slot="reference" class="el-icon-warning-outline icon-tl"></i>
          </el-popover>

          <div class="title">{{ item.label }}</div>
          <div class="num">{{ item.num }}</div>
        </div>
      </el-col>
    </el-row>


    <!-- 2. 饼图 + 柱图 -->
    <el-row type="flex" :gutter="20" style="margin-top:16px;">
      <el-col :span="12">
        <Title title="设备状态分布" />
        <div class="chart-card curve-card">
          <div ref="left2" style="height:150px;"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <Title title="服务事项概览" />
        <div class="chart-card curve-card">
          <div ref="bottom1" style="height:150px;"></div>
        </div>
      </el-col>
    </el-row>

    <!-- 3. 实时温湿度曲线 + 实时颗粒物条形图（同一排） -->
    <el-row type="flex" :gutter="20" style="margin-top:16px;">
      <el-col :span="12">
        <Title title="实时温湿度曲线" />
        <div class="chart-card curve-card">
          <div ref="right1" style="height:150px;"></div> <!-- ← 缩小 -->
        </div>
      </el-col>
      <el-col :span="12">
        <Title title="实时颗粒物" />
        <div class="chart-card curve-card">
          <div ref="particle" style="height:150px;"></div> <!-- 新条形图容器 -->
        </div>
      </el-col>
    </el-row>

    <!-- 4. 地图：设备点 + 监测点 -->
    <el-row type="flex" style="margin-top:16px;">
      <el-col :span="24">
        <Title title="地图概览" />
        <div class="chart-card map-card curve-card" style="width: 100%;">
          <div ref="map" style="width: 100%;" class="map-container"></div>
        </div>
      </el-col>
    </el-row>

  </div>
</template>

<script>
/* ---------- 图表依赖 ---------- */
import { Column, Pie, DualAxes, Bar } from '@antv/g2plot'   // ← 新增 Bar
import axios from 'axios'
import { get } from '@/utils/request'
import { mapState, mapMutations } from 'vuex'
import moment from 'moment'

/* ---------- 高德加载器 ---------- */
const loadAMap = () =>
  new Promise((resolve, reject) => {
    if (window.AMap) return resolve(window.AMap)
    const script = document.createElement('script')
    script.src = 'https://webapi.amap.com/loader.js'
    script.onload = () => {
      window.AMapLoader.load({
        key: 'ddabbefeec9e1bc78ef33454e278e7ac',
        version: '2.0'
      })
        .then(() => resolve(window.AMap))
        .catch(err => reject(err))
    }
    script.onerror = reject
    document.head.appendChild(script)
  })

export default {
  name: 'DashboardUnified',
  data() {
    return {
      data: [],
      serData: [],
      column: null,
      empData: [],
      humData: [],
      dualAxes: null,
      params: { page: 1, pageSize: 100 },
      deviceData: [],
      monitorData: [],
      particleBar: null,          // 颗粒物条形图实例
      particleData: []            // 颗粒物数据
    }
  },
  computed: { ...mapState(['ed']) },
  watch: {
    ed: { handler(n) { this.params.engineer_id = n.engineer_id; this.params.device_id = n.device_id; this.getSerData(); this.getHumData(); this.getParticleData() }, deep: true }
  },
  methods: {
    ...mapMutations(['SET_ED']),
    /* ---------- 颗粒物条形图 ---------- */
    async getParticleData() {
      const res = await get('/dashboard/pageQueryTodayData', this.params)
      const list = (res.data.list || []).filter((_, idx) => idx % 10 === 0)
      console.log(this.particleData, '22222222');
      this.particleData = list.map(item => ({
        time: moment(item.insert_time).format('HH:mm'),
        pm25: Number(item.pm25 || 0)
      }))
      this.particleBar ? this.particleBar.changeData(this.particleData) : this.loadParticleBar()
    },

    loadParticleBar() {
      this.particleBar = new Bar(this.$refs.particle, {
        data: this.particleData,
        xField: 'time',
        yField: 'pm25',
        color: ({ pm25 }) => {
          if (pm25 > 115) return '#677467' // .color-0
          if (pm25 > 75) return '#9bab7e'  // .color-1
          if (pm25 > 35) return '#b7c49a'  // .color-2
          return '#dfe1c0'                 // .color-3
        },
        padding: [8, 8, 20, 30],
        legend: false,
        yAxis: false,
        xAxis: {
          label: {
            style: { fill: '#333', fontSize: 12, rotate: 45, textAlign: 'end' }
          }
        },
        tooltip: {
          formatter: (d) => ({ name: d.time, value: `${d.pm25} μg/m³` })
        }
      })
      this.particleBar.render()
    }
    ,

    /* ---------- 原图表 ---------- */
    async fetchIndicators() {
      const { data: res } = await axios.get('http://120.55.3.147:7001/count/countAll')
      const map = {
        '设备总数': 'Total Devices',
        '在线设备数': 'Online Devices',
        '离线设备数': 'Offline Devices',
        '工程总数': 'Total Projects',
        '工单总数': 'Total Work Orders'
      }
      this.data = [
        { label: 'Total Devices', num: 5, tip: '设备总数' },
        { label: 'Online Devices', num: 4, tip: '在线设备数' },
        { label: 'Offline Devices', num: 1, tip: '离线设备数' },
        { label: 'Total Projects', num: 5, tip: '工程总数' },
        { label: 'Total Work Orders', num: 9, tip: '工单总数' }
      ]
    },
    async getSerData() {
      const res = await get('dashboard/queryEngineerBindDeviceNumber')
      this.serData = res.data
      this.column ? this.column.changeData(this.serData) : this.loadColumn()
    },
    loadColumn() {
      /* 中文 → 英文映射（不变） */
      const nameMap = {
        '山西农大主体育场工程': 'Shanxi Stadium',
        '太原理工大学一号教学楼工程': 'TYUT Bldg-1',
        '中北大学': 'NUC',
        '兰州理工大学': 'LUT',
        '测试工程': 'Test'
      }
      const enData = this.serData.map(d => ({ ...d, type: nameMap[d.type] || d.type }))

      this.column = new Column(this.$refs.bottom1, {
        data: enData,
        xField: 'type',
        yField: 'value',
        padding: [8, 8, 20, 30],
        legend: false,
        yAxis: false,
        meta: { type: { alias: '' }, value: { alias: '' } },
        color: ({ type }) => {
          const colors = {
            'Shanxi Stadium': '#677467',
            'TYUT Bldg-1': '#9bab7e',
            'NUC': '#b7c49a',
            'LUT': '#dfe1c0',
            'Test': '#d2d8b2'
          }
          return colors[type] || '#d2d8b2'
        },
        xAxis: {
          label: {
            style: { fill: '#4d4f58', fontSize: 12, rotate: 45, textAlign: 'end' }
          }
        }
      })
      this.column.render()
    },
    async getEmpData() {
      const res = await get('/dashboard/queryDeviceOnlineNumber')
      this.empData = res.data
      this.loadPie()
    },
    loadPie() {
      const labelMap = {
        '在线': 'Online',
        '离线': 'Offline'
      }
      const enData = this.empData.map(d => ({
        ...d,
        type: labelMap[d.type] || d.type
      }))

      new Pie(this.$refs.left2, {
        data: enData,
        angleField: 'value',
        colorField: 'type',
        color: ({ type }) => (type === 'Online' ? '#677467' : '#9bab7e'),
        radius: 0.8,
        label: { type: 'outer', content: '{name} {value}', style: { fill: '#4d4f58' } },
        legend: { position: 'top', itemName: { style: { fill: '#4d4f58' } } },
        interactions: [{ type: 'pie-legend-active' }, { type: 'element-active' }]
      }).render()
    }
    ,
    async getHumData() {
      const res = await get('/dashboard/pageQueryTodayData', this.params)
      const temp = []
      res.data.list.forEach((item, idx) => {
        if (idx % 10 === 0) {
          item.insert_time = moment(item.insert_time).format('HH:mm')
          temp.push(item)
        }
      })
      this.humData = temp
      this.dualAxes ? this.dualAxes.changeData([this.humData, this.humData]) : this.loadDualAxes()
    },
    loadDualAxes() {
      this.dualAxes = new DualAxes(this.$refs.right1, {
        data: [this.humData, this.humData],
        xField: 'insert_time',
        yField: ['temperature', 'humidity'],
        geometryOptions: [
          { geometry: 'line', color: '#677467' },
          { geometry: 'line', color: '#9bab7e' }
        ]
      })
      this.dualAxes.render()
    },

    /* ---------- 地图 ---------- */
    async loadMap() {
      const AMap = await loadAMap()
      const map = new AMap.Map(this.$refs.map, {
        viewMode: '3D',
        pitch: 50,
        rotation: -15,
        zoom: 14,
        zooms: [2, 20],
        center: [103.76, 36.07],
        terrain: true,
        rotateEnable: true,
        pitchEnable: true
      })
      map.add(new AMap.TileLayer.Traffic({ autoRefresh: true, interval: 180 }))
      AMap.plugin(['AMap.ToolBar', 'AMap.HawkEye'], () => {
        map.addControl(new AMap.ToolBar({ position: 'LB' }))
        map.addControl(new AMap.HawkEye())
      })

      this.deviceData.forEach(item => {
        const marker = new AMap.Marker({
          position: item.position,
          title: item.name,
          extData: item
        })
        marker.on('click', () => {
          this.SET_ED({
            engineer_id: item.engineer_id,
            device_id: item.id
          })
        })
        map.add(marker)
      })

      this.monitorData.forEach(pt => {
        const marker = new AMap.Marker({
          position: pt.position,
          title: pt.name,
          extData: pt,
          icon: new AMap.Icon({
            type: 'image',
            image: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker-green.png',
            size: new AMap.Size(16, 16),
            imageSize: new AMap.Size(16, 16)
          })
        })
        marker.on('click', function () {
          console.log('[监测点]', this.getExtData())
        })
        map.add(marker)
      })
    },

    /* ---------- 数据获取 ---------- */
    async fetchAll() {
      const [device, monitor] = await Promise.all([
        get('/dashboard/findEngineerDeviceTree'),
        get('/dashboard/findEngineerDeviceTree'),
        // get('/dashboard/findMonitorPoints')
      ])
      const temp = []
      device.data.forEach(p => p.children?.forEach(c => temp.push(c)))
      this.deviceData = temp
      this.monitorData = monitor.data || []
    }
  },

  async mounted() {
    await Promise.all([
      this.fetchIndicators(),
      this.getEmpData(),
      this.getSerData(),
      this.getHumData(),
      this.fetchAll()
    ]);
    this.getParticleData();
    this.loadMap()
    this.loadParticleBar()   // ← 初始化颗粒物条形图
  }
}
</script>

<style scoped>
/* 统一上下留白 */
.el-row {
  margin-top: 24px !important;
  margin-bottom: 0 !important;
}

.chart-card {
  padding: 12px;
  margin-top: 8px;
  margin-bottom: 8px;
}


/* ---------- 五个方块配色 ---------- */
.grid-box {
  position: relative;
  height: 80px;
  color: #4d4f58;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, .08);
}

/* 右上角图标 */
.icon-tl {
  position: absolute;
  top: 8px;
  right: 6px;
  font-size: 16px;
  color: #4d4f58;
  opacity: .9;
  cursor: pointer;
}

.color-0 {
  background: linear-gradient(135deg, #677467 0%, #677467 100%);
}

.color-1 {
  background: linear-gradient(135deg, #9bab7e 0%, #9bab7e 100%);
}

.color-2 {
  background: linear-gradient(135deg, #b7c49a 0%, #b7c49a 100%);
}

.color-3 {
  background: linear-gradient(135deg, #dfe1c0 0%, #dfe1c0 100%);
}

.color-4 {
  background: linear-gradient(135deg, #d2d8b2 0%, #d2d8b2 100%);
}

.title {
  font-size: 14px;
  margin-bottom: 4px;
  opacity: .9;
}

.num {
  font-size: 24px;
  font-weight: 600;
}

.chart-card {
  background: rgba(255, 253, 250, 0.85);
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, .05);
  padding: 8px;
}

/* 统一曲线/地图卡片背景色 */
.curve-card {
  background: linear-gradient(135deg, #677467 0%, #dfe1c0 100%);
  color: #333;
}

.map-card {
  padding: 0;
  overflow: hidden;
}

.map-container {
  width: 100%;
  height: 260px;
  margin-top: 8px;
  margin-bottom: 8px;
}

/* 再小改这里 */
.page-box {
  min-height: 100vh;
  padding: 16px;
  /* background: #364433; */
  background: url(~@/assets/wallpaper.jpg) center/cover no-repeat fixed;
}

.icon-tl {
  position: absolute;
  top: 6px;
  right: 6px;
  font-size: 16px;
  color: #000;
  /* 黑色图标 */
  cursor: pointer;
}

/* 地图卡片相对定位，给日历当锚点 */
.map-card {
  position: relative;
  padding: 0;
  overflow: visible;
  /* 让日历可以超出卡片 */
}

/* 迷你日历 */
.mini-cal {
  position: absolute;
  right: 8px;
  bottom: 8px;
  width: 240px;
  /* 想多小自己调 */
  background: rgba(255, 255, 255, 0.65);
  backdrop-filter: blur(6px);
  border: 1px solid rgba(255, 255, 255, 0.4);
  border-radius: 8px;
  font-size: 12px;
  /* 整体字号缩小 */

  /* 去掉 Element 自带阴影 & 边框 */
  box-shadow: none;

  /* 隐藏「上月/下月」按钮，更简洁 */
  ::v-deep .el-calendar__button-group {
    display: none;
  }

  /* 日期格子高度压缩 */
  ::v-deep .el-calendar-table td {
    padding: 2px 0;
    height: 20px;
  }

  ::v-deep .el-calendar-day {
    height: 20px;
    line-height: 20px;
    padding: 0;
    text-align: center;
  }
}
</style>